package com.learn.security.theory.asymmetric_encryption;


import com.learn.security.utils.asymmetric_encryption.DHUtil;

import java.util.Map;

/**
 * DH算法
 */
public class DHTest {

    private static final String encodeStr = "dh test";
    private static final String encodeStr2 = "dh2 test";

    public static void main(String[] args) {

        DHUtil();

    }

    private static void DHUtil() {
        Map<String, Object> aKeyMap = DHUtil.initKey();
        String aPublicKey = DHUtil.getPublicKey(aKeyMap);
        String aPrivateKey = DHUtil.getPrivateKey(aKeyMap);

        System.err.println("甲方公钥:" + aPublicKey);
        System.err.println("甲方私钥:" + aPrivateKey);

        // 由甲方公钥产生本地密钥对儿
        Map<String, Object> bKeyMap = DHUtil.initKey(aPublicKey);
        String bPublicKey = DHUtil.getPublicKey(bKeyMap);
        String bPrivateKey = DHUtil.getPrivateKey(bKeyMap);

        System.err.println("乙方公钥:" + bPublicKey);
        System.err.println("乙方私钥:" + bPrivateKey);
        System.err.println("原文: " + encodeStr);

        // 由甲方公钥，乙方私钥构建密文
        byte[] aCode = DHUtil.encrypt(encodeStr.getBytes(), aPublicKey,
                bPrivateKey);
        System.out.println("密文: " + DHUtil.encryptBASE64(aCode));

        // 由乙方公钥，甲方私钥解密
        byte[] aDecode = DHUtil.decrypt(aCode, bPublicKey, aPrivateKey);
        String aOutput = aDecode == null ? null : (new String(aDecode));

        System.err.println("解密: " + aOutput);

        System.err.println(" ===============反过来加密解密================== ");
        System.err.println("原文: " + encodeStr2);

        // 由乙方公钥，甲方私钥构建密文
        byte[] bCode = DHUtil.encrypt(encodeStr2.getBytes(), bPublicKey,
                aPrivateKey);
        System.out.println("密文: " + DHUtil.encryptBASE64(bCode));

        // 由甲方公钥，乙方私钥解密
        byte[] bDecode = DHUtil.decrypt(bCode, aPublicKey, bPrivateKey);
        String bOutput = bDecode == null ? null : (new String(bDecode));

        System.err.println("解密: " + bOutput);
    }
}


